import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';
import { Server } from 'socket.io';

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const httpServer = createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    handle(req, res, parsedUrl);
  });

  const io = new Server(httpServer, {
    cors: { origin: "*" }
  });

  io.on('connection', (socket) => {
    console.log('客户端已连接:', socket.id);

    socket.on('offer', (data) => {
      socket.broadcast.emit('offer', data);
    });

    socket.on('answer', (data) => {
      socket.broadcast.emit('answer', data);
    });

    socket.on('candidate', (data) => {
      socket.broadcast.emit('candidate', data);
    });

    socket.on('disconnect', () => {
      console.log('客户端断开:', socket.id);
    });
  });

  httpServer.listen(5050, () => {
    console.log('Server running on http://localhost:5050');
  });
});